package com.example.shop_front_api.config;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "qiniu.enabled", havingValue = "true", matchIfMissing = true)
public class QiniuConfig {

    @Value("${qiniu.access-key:default-access-key}")
    private String accessKey;

    @Value("${qiniu.secret-key:default-secret-key}")
    private String secretKey;

    @Value("${qiniu.bucket:default-bucket}")
    private String bucket;

    @Value("${qiniu.domain:https://default.com}")
    private String domain;

    @Bean
    public Auth auth() {
        // 检查是否是默认值
        if ("default-access-key".equals(accessKey) || "default-secret-key".equals(secretKey)) {
            System.out.println("⚠️ 七牛云配置提醒：当前使用默认配置，请完成七牛云实名认证后配置真实密钥");
            // 返回模拟的Auth对象避免NPE
            return Auth.create("default-access-key", "default-secret-key");
        }
        return Auth.create(accessKey, secretKey);
    }

    @Bean
    public com.qiniu.storage.Configuration qiniuConfiguration() {
        return new com.qiniu.storage.Configuration(Region.autoRegion());
    }

    @Bean
    public UploadManager uploadManager(com.qiniu.storage.Configuration cfg) {
        return new UploadManager(cfg);
    }

    @Bean
    public BucketManager bucketManager(Auth auth, com.qiniu.storage.Configuration qiniuConfiguration) {
        return new BucketManager(auth, qiniuConfiguration);
    }

    public String getBucket() {
        return bucket;
    }

    public String getDomain() {
        return domain;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }
}